package com.sun.future;

import java.util.concurrent.*;

public class RunAsyncExample {

    private static final ExecutorService customExecutor = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 1. 使用默认线程池
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("runAsync任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            System.out.println("runAsync任务完成");
        });

        // 2. 使用自定义线程池
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            System.out.println("runAsync任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            System.out.println("runAsync任务完成");
        }, customExecutor);

        // 等待任务完成
        future1.get();
        future2.get();

        System.out.println("主线程结束");
        customExecutor.shutdown();
    }
}
